package com.zoe.vhr.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.zoe.vhr.enums.RedisKeyEnum;
import com.zoe.vhr.mapper.MenuMapper;
import com.zoe.vhr.model.Hr;
import com.zoe.vhr.model.Menu;
import com.zoe.vhr.service.MenuService;
import com.zoe.vhr.util.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author Zoe.Zhang
 * @Date: 2021/07/29
 * @Description
 */
@Service
@Transactional
public class MenuServiceImpl implements MenuService {
    @Autowired
    MenuMapper menuMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    List<Menu> buildMenuTrees(Integer parentId, List<Menu> menus) {
        List<Menu> collect = menus.stream()
            .filter(menu -> ObjectUtil.equal(menu.getParentId(), parentId))
            .peek((menu -> menu.setChildren(buildMenuTrees(menu.getId(), menus)))).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<Menu> listMenusByRoleId() {
        Hr hr = SecurityUtil.getCurrentUser();
        List<Menu> menus = menuMapper.listMenusByRoleId(hr.getId());
        List<Menu> menuTrees = buildMenuTrees(1, menus);
        return menuTrees;
    }


    @Override
    public List<Menu> listMenusByRid() {
        Hr hr = SecurityUtil.getCurrentUser();
        List<Menu> menus = menuMapper.listMenusByRId(hr.getId());
        return menus;
    }

    @Override
    public List<Menu> listMenusAndRoleId() {
        return menuMapper.listMenusAndRoleId();
    }

    @Override
    public List<Menu> listAllMenus() {
        List<Menu> menus = menuMapper.listAllMenus();
        return buildMenuTrees(1, menus);
    }

    @Override
    public List<Integer> listCheckedMenus(Integer roleId) {
        return menuMapper.listCheckedMenus(roleId);
    }

    @Override
    public int updateMenuWithRole(Integer roleId, Integer[] menuIds) {
        int count = menuMapper.deleteMenuRoleByRoleId(roleId);
        int saveCount = 0;
        if (ArrayUtil.isNotEmpty(menuIds)) {
            saveCount = menuMapper.saveMenuWithRole(roleId, menuIds);
        }
        redisTemplate.convertAndSend(RedisKeyEnum.REFRESH_MENU_TOPIC.getKey(), "刷新菜单数据~~~~");
        return saveCount;
    }
}
